package com.dqp.cslggroup.JWXT;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.bumptech.glide.Glide;
import com.dd.morphingbutton.impl.IndeterminateProgressButton;
import com.dqp.cslggroup.Api.appApi;
import com.dqp.cslggroup.ConnectNet.connectJWXT;
import com.dqp.cslggroup.ConnectSever.Send;
import com.dqp.cslggroup.ConnectSever.SeverIP;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.ProgressButton.LinearProgressButtonUtil;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.NoUnderlineSpan;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.bean.Club;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

public class login_JWXT extends BaseActivity {
    private String url = "http://10.28.200.187";
    private EditText userin;
    private EditText pwdin;
    private String stuNum = null, password = null, use_url;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private TextView tip;
    private RadioButton nei, wai;
    private LinearLayout root_view;
    private IndeterminateProgressButton btnMorph1;
    private LinearProgressButtonUtil progressButtonUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_jwxt);
        EventBus.getDefault().register(this);
        initComp();
        rem_password();
        UiUtils.addLayoutListener(root_view, tip);
        if (NetCheckUtil.checkNet(login_JWXT.this)) {
            selLoginImg("jwxt");
            selectUrl();
            initFunc();
        } else ToastUtil.showToast("请连接网络！");
    }

    public void selLoginImg(String stype) {
        new Thread(() -> {
            Club club;
            ArrayList<Club> dataList = appApi.getLoginImg();
            for (int i = 0; i < dataList.size(); i++) {
                club = dataList.get(i);
                if (club.getClub_des().equals(stype)) {
                    EventBus.getDefault().post(new MessageEvent("login_JWXT", 2, club));
                }
            }

        }).start();
    }

    private void selectUrl() {
        if (nei.isChecked()) {
            use_url = url;
        } else if (wai.isChecked()) {
            SharedPreferences sp;
            SharedPreferences.Editor editor;
            sp = PreferenceManager.getDefaultSharedPreferences(this);
            editor = sp.edit();
            String ip = sp.getString("ip", SeverIP.getDefvalueUrl());
            editor.apply();
            use_url = ip + ":8887";
        }
    }


    public void rem_password() {
        sp = PreferenceManager.getDefaultSharedPreferences(login_JWXT.this);
        pwdin.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        boolean isRemember = sp.getBoolean("remember_JWXT_password", false);
        if (isRemember) {
            stuNum = sp.getString("stuNum_JWXT", "");
            password = sp.getString("password_JWXT", "");
            userin.setText(stuNum);
            pwdin.setText(password);
            editor = sp.edit();
            editor.putBoolean("remember_JWXT_password", true);
            editor.putString("stuNum_JWXT", stuNum);
            editor.putString("password_JWXT", password);
            editor.apply();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initComp() {
        tip = findViewById(R.id.jwxt_frag_tv_tishi);
        tip.setMovementMethod(LinkMovementMethod.getInstance());
        NoUnderlineSpan mNoUnderlineSpan = new NoUnderlineSpan();
        if (tip.getText() instanceof Spannable) {
            Spannable s = (Spannable) tip.getText();
            s.setSpan(mNoUnderlineSpan, 0, s.length(), Spanned.SPAN_MARK_MARK);
        }
        userin = findViewById(R.id.jwxt_username);
        pwdin = findViewById(R.id.jwxt_password);
        LinearLayout relativeLayout = findViewById(R.id.jwxt_yz_rel);
        relativeLayout.setVisibility(View.GONE);
        nei = findViewById(R.id.jwxt_nei);
        wai = findViewById(R.id.jwxt_wai);
        root_view = findViewById(R.id.root_view);
        RadioGroup radioGroup = findViewById(R.id.wang);
        progressButtonUtil = new LinearProgressButtonUtil(this);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (nei.isChecked()) {
                use_url = url;
                ToastUtil.showToast("请先连接校园网后登录！");
            } else if (wai.isChecked()) {
                SharedPreferences sp;
                SharedPreferences.Editor editor;
                sp = PreferenceManager.getDefaultSharedPreferences(this);
                editor = sp.edit();
                String ip = sp.getString("ip", "47.96.190.22");
                editor.apply();
                use_url = ip + ":8887";
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void initFunc() {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        btnMorph1 = findViewById(R.id.btnMorph);
        progressButtonUtil.IPBmorphToSquare(btnMorph1, 0);
        btnMorph1.setOnClickListener(view -> {
            if (userin.getText().toString().isEmpty()) {
                ToastUtil.showToast("请输入学号！");
            } else if (pwdin.getText().toString().isEmpty()) {
                ToastUtil.showToast("请输入密码！");
            } else {
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (btnMorph1.getText().equals("登录")) {
                    progressButtonUtil.IPBonMorphButtonClicked(btnMorph1);
                    stuNum = userin.getText().toString();
                    password = pwdin.getText().toString();
                    new Thread(this::login).start();
                } else {
                    progressButtonUtil.IPBmorphToSquare(btnMorph1, progressButtonUtil.integer(R.integer.mb_animation));
                }
            }
        });
    }

    public void login() {
        connectJWXT connectJWXT = new connectJWXT(use_url, stuNum, password);
        try {
            int key;
            //connectJWXT.init();
            key = connectJWXT.loginByJsoup();
            Map<String, String> cookies = connectJWXT.sendCookie();
            if (key == 1) {
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 0, null));
                editor = sp.edit();
                editor.putBoolean("remember_JWXT_password", true);
                editor.putString("stuNum_JWXT", stuNum);
                editor.putString("password_JWXT", password);
                editor.apply();
                Send.jwxtPv();
                finish();
                Intent intent = new Intent(login_JWXT.this, JWXT_main.class);
                intent.putExtra("cookies", (Serializable) cookies);
                intent.putExtra("stuNum", stuNum);
                intent.putExtra("url", use_url);
                intent.setClass(login_JWXT.this, JWXT_main.class);
                startActivity(intent);
            } else if (key == 2) {
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 1, null));
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 3, null));
                ToastUtil.showToast("用户名或密码错误!");
            } else if (key == 3) {
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 1, null));
                ToastUtil.showToast("验证码错误!");
            } else if (key == 4) {
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 1, null));
                ToastUtil.showToast("验证码不能为空！");
            } else {
                EventBus.getDefault().post(new MessageEvent("login_JWXT", 1, null));
                ToastUtil.showToast("登录出错！请重新登录！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            EventBus.getDefault().post(new MessageEvent("login_JWXT", 1, null));
            if (nei.isChecked())
                ToastUtil.showToast("内网模式必须连接校园网进行登录！");
            else ToastUtil.showToast("登录出现了一点小问题！请重新登录！");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("login_JWXT")) {
            if (event.getWhat() == 0) {
                progressButtonUtil.IPBmorphToSuccess(btnMorph1);
            }
            if (event.getWhat() == 1) {
                progressButtonUtil.IPBmorphToFailure(btnMorph1, 500);
            }
            if (event.getWhat() == 2) {
                ImageView bg = findViewById(R.id.jwxt_img);
                TextView title = findViewById(R.id.jwxt_img_title);
                Club club = (Club) event.getObj();
                title.setText(club.getClub_name());
                Glide.with(login_JWXT.this).load(club.getClub_img()).into(bg);
            }
            if (event.getWhat() == 3) {
                Button rember = findViewById(R.id.quick_login);
                rember.setText("忘记密码？");
                rember.setTextColor(getResources().getColor(R.color.red));
                rember.setVisibility(View.VISIBLE);
                rember.setOnClickListener(v -> ToastUtil.showLongToast("教务系统密码找回请咨询班主任！"));
            }
        }

    }
}
